package com.atguigu.mvc.controller;

import com.atguigu.mvc.bean.User;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 陆小根
 * date: 2022/05/02
 * Description:
 */

@Controller
public class HttpController {

  @RequestMapping(value = "/testRequestBody", method = RequestMethod.POST)
  public String testRequestBody(@RequestBody String requestBody) {
    System.out.println("requestBody = " + requestBody);

    return "success";
  }

  @RequestMapping(value = "/testRequestEntity", method = RequestMethod.POST)
  public String testRequestEntity(RequestEntity<String> requestEntity) {
    // 当前requestEntity表示整个请求报文的信息
    System.out.println("请求头:" + requestEntity.getHeaders());
    System.out.println("请求体:" + requestEntity.getBody()); // 只有post请求才有请求体

    return "success";
  }

  @RequestMapping("/testResponse")
  public void testResponse(HttpServletResponse response) throws IOException {
    // 响应体就是我们看到的页面
    response.getWriter().write("hello,response");
  }

  @RequestMapping("testResponseBody")
  @ResponseBody // 可以将方法的返回值直接作为响应报文的响应体应用到浏览器
  public String testRequestBody() {
    return "hello,ResponseBody";
  }

  // 处理json数据
  @RequestMapping("/testResponseUser")
  @ResponseBody
  public User testResponseUser() {
    // 服务器接收的是JSON字符串
    return new User(1001, "admin", "123456", 23, "男");
  }

  // chuli  ajax
  @RequestMapping("/testAxios")
  @ResponseBody
  public String testAjax(String username, String password) {
    System.out.println("username = " + username);
    System.out.println("password = " + password);
    return "hello,ajax";
  }

}
